package cn.pconline.autoclub.web.app;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.DynaImage;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.Subject;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.DynaService;
import cn.pconline.autoclub.service.SubjectDynaService;
import cn.pconline.autoclub.service.SubjectService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.BrandIdUrlMap;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.app.AppControllerStatic;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @author zhouruxuan
 * @date 2015年4月23日 上午10:12:06
 */
@Controller
@RequestMapping(value = "/appapi")
public class AppSubjectController {
	
	@Autowired
	private SubjectService subjectService;
	@Autowired
	private SubjectDynaService subjectDynaService;
	@Autowired
	private DynaService dynaService;
	@Autowired
	private UserService userService;
	@Autowired
	private SystemConfig systemConfig;
	
    /**话题列表默认一页记录大小**/
    private static final int LIST_TOPIC_DEF_PAGE_SIZE = 30;
    
	/**
	 * 获取最热话题列表
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/1.0/subject/hotSubjectList.do", method=RequestMethod.GET)
	public void hotSubjectList(HttpServletRequest request, HttpServletResponse response) {
		WebUtils.setEncoding4App(request, response);
		String callback = AppControllerStatic.paramCallback(request);
        int xssEncode = AppControllerStatic.paramXssEncode(request);
        int pageNo = AppControllerStatic.paramPageNo(request);
        int pageSize = AppControllerStatic.paramPageSize(request);
		
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		
//		Pager<Subject> pager = subjectService.pageSubjectByHot(pageNo, pageSize);
		
		//本周话题
        Date beginDate = DateUtils.getSingleDateBefore(new Date(), 7);
        Pager<Subject> pager = subjectService.pageSubjectByHot(pageNo,pageSize,beginDate);
        List<Subject> subjects = new ArrayList<Subject>();
        subjects.addAll(pager.getResultList());
        if(subjects.size()<pageSize && pageNo==1){
        	Pager<Subject> pagerAdd = subjectService.pageSubjectByNew(pageNo, LIST_TOPIC_DEF_PAGE_SIZE);
        	
        	for(Subject subject : pagerAdd.getResultList()){
        		Boolean flag = false;
        		for(Subject subject2 : pager.getResultList()){
        			if(subject.getSubjectId() == subject2.getSubjectId()){
        				flag =true;
        				break;
        			}
        		}
        		if(!flag){
        			subjects.add(subject);
        		}
        		
        	}
        	
        	
        	//按pv排序
        	Collections.sort(subjects, new Comparator<Subject>() {
                @Override
                public int compare(Subject s1, Subject s2) {
                    return (int) (s2.getPvCount() - s1.getPvCount());
                }
            });
        	pager.setResultList(subjects);
        }
        
		
		if(pager != null && !pager.getResultList().isEmpty()) {
			for(Subject subject : pager.getResultList()) {
				JSONObject json = new JSONObject();
				json.put("subjectId", subject.getSubjectId());
				String title = subject.getTitle();
				json.put("title", xssEncode == 0 ? title : EncodeUtils.encodeForHTMLFilterNull(title));
				String description = subject.getIntroduction();
				json.put("description", xssEncode == 0 ? description : EncodeUtils.encodeForHTMLFilterNull(description));
				String logo = subject.getLogo();
				json.put("logo", logo == null ? subject.getDefaultLogo() : logo);
				jsonArray.add(json);
			}
		}
		
		jsonObject.put("subjectList", jsonArray);
		AppControllerStatic.printSuccessMsgPager(response, jsonObject, callback, pager, AppControllerStatic.V1_VERSION_LATEST);
	}
	
	/**
	 * 获取话题详情(最新排序）
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/1.0/subject/subjectDetailByCreateDate.do", method=RequestMethod.GET)
	public void subjectDetailByCreateDate(HttpServletRequest request, HttpServletResponse response) {
		WebUtils.setEncoding4App(request, response);
		
		String callback = AppControllerStatic.paramCallback(request);
        int xssEncode = AppControllerStatic.paramXssEncode(request);
        int pageNo = AppControllerStatic.paramPageNo(request);
        int pageSize = AppControllerStatic.paramPageSize(request);
        long subjectId = WebUtils.paramLong(request, "subjectId", 0L);
        String title = WebUtils.param(request, "title", "");
        title = title.trim();
        title = "#" + title+ "#";
		
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		
		Subject subject;
		//如果subjectId, tile两个参数同时存在，以subjectId为准
		if(subjectId > 0) {
			subject = subjectService.findSubjectById(subjectId);
			if(subject != null) {
				title = subject.getTitle();
			}
		} else {
			subject = subjectService.findByTitle(title);
			if(subject != null) {
				subjectId = subject.getSubjectId();
			}
		}
		
		//判断话题是否存在
		if(subject == null) {
			AppControllerStatic.printErrorMsg(response, "话题不存在", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
			return;
		}
		
		//话题内容
		jsonObject.put("subjectId", subjectId);
		jsonObject.put("title", title);
		String description = subject.getIntroduction();
		jsonObject.put("description", xssEncode == 0 ? description : EncodeUtils.encodeForHTMLFilterNull(description));
		jsonObject.put("logo", subject.getLogo() == null ? subject.getDefaultLogo() : subject.getLogo());
		jsonObject.put("replyCount", subject.getReplyCount());
		jsonObject.put("pvCount", subject.getPvCount());
		
		Pager<DynaInfo> pager = subjectDynaService.pageDynaBySubjectIdOrderNew(subjectId, pageNo, pageSize, Subject.ALL_DATA);
		jsonArray = this.getSubjectDynaList(pager, xssEncode);
		
		jsonObject.put("dynaList", jsonArray);
		AppControllerStatic.printSuccessMsgPager(response, jsonObject, callback, pager, AppControllerStatic.V1_VERSION_LATEST);
	}
	
	/**
	 * 获取话题详情(最热排序）
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/1.0/subject/subjectDetailByPostCont.do", method=RequestMethod.GET)
	public void subjectDetailByPostCont(HttpServletRequest request, HttpServletResponse response) {
		WebUtils.setEncoding4App(request, response);
		
		String callback = AppControllerStatic.paramCallback(request);
        int xssEncode = AppControllerStatic.paramXssEncode(request);
        int pageNo = AppControllerStatic.paramPageNo(request);
        int pageSize = AppControllerStatic.paramPageSize(request);
        long subjectId = WebUtils.paramLong(request, "subjectId", 0L);
        String title = WebUtils.param(request, "title", "");
        title = title.trim();
        title = "#" + title + "#";
		
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		
		Subject subject;
		//如果subjectId, tile两个参数同时存在，以subjectId为准
		if(subjectId > 0) {
			subject = subjectService.findSubjectById(subjectId);
			if(subject != null) {
				title = subject.getTitle();
			}
		} else {
			subject = subjectService.findByTitle(title);
			if(subject != null) {
				subjectId = subject.getSubjectId();
			}
		}
		
		//判断话题是否存在
		if(subject == null) {
			AppControllerStatic.printErrorMsg(response, "话题不存在", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
			return;
		}
		
		//话题内容
		jsonObject.put("subjectId", subjectId);
		jsonObject.put("title", title);
		String description = subject.getIntroduction();
		jsonObject.put("description", xssEncode == 0 ? description : EncodeUtils.encodeForHTMLFilterNull(description));
		String logo = subject.getLogo();
		jsonObject.put("logo", logo == null ? subject.getDefaultLogo() : logo);
		jsonObject.put("replyCount", subject.getReplyCount());
		jsonObject.put("pvCount", subject.getPvCount());
		
		Pager<DynaInfo> pager = subjectDynaService.pageDynaBySubjectIdOrderReply(subjectId, pageNo, pageSize, Subject.ALL_DATA);
		jsonArray = this.getSubjectDynaList(pager, xssEncode);
		
		jsonObject.put("dynaList", jsonArray);
		AppControllerStatic.printSuccessMsgPager(response, jsonObject, callback, pager, AppControllerStatic.V1_VERSION_LATEST);
	}
	
	/**
	 * 获取话题说说列表
	 * @param pager
	 * @return
	 */
	private JSONArray getSubjectDynaList(Pager<DynaInfo> pager, int xssEncode) {
		JSONArray jsonArray = new JSONArray();
		if(pager != null && !pager.getResultList().isEmpty()) {
			for(DynaInfo dynaInfo : pager.getResultList()) {
				JSONObject json = new JSONObject();
				long dynaInfoId = dynaInfo.getDynaInfoId();
				json.put("dynaInfoId", dynaInfoId);
				String content = dynaInfo.getContent();
				content = xssEncode == 0 ? content : EncodeUtils.encodeForHTMLFilterNull(content);
				json.put("content", content);
				json.put("postCount", dynaInfo.getPostCount());
				json.put("praiseCount", dynaInfo.getPraiseCount());
				json.put("createAt", dynaInfo.getCreateAt());
				long createBy = dynaInfo.getCreateBy();
				json.put("createBy", createBy);
				//获取认证用户的品牌图标
				String brandLogo = "";
				User user = userService.findUser(createBy);
				if(user != null) {
					json.put("nickName", user.getNickname());
					int isVip = user.getVip();
					json.put("isVip", user.getVip());
					if(isVip == User.IS_VIP) {
						String vipInfo = user.getVipInfo();
						brandLogo = BrandIdUrlMap.getBrandLogo(vipInfo);
					}
					
				}
				json.put("brandLogo", brandLogo);
				
				List<DynaImage> dynaImages = dynaService.getImagesByDynaInfoId(dynaInfoId, 9);
				JSONArray imageJsonArray = new JSONArray();
				for(DynaImage dynaImage : dynaImages) {
					JSONObject imageJsonObject = new JSONObject();
					imageJsonObject.put("seq", dynaImage.getSeq());
					imageJsonObject.put("url", dynaImage.getUrl500x500());
					imageJsonObject.put("width", dynaImage.getWidth());
					imageJsonObject.put("height", dynaImage.getHeight());
					imageJsonArray.add(imageJsonObject);
				}
				json.put("images", imageJsonArray);
				
				jsonArray.add(json);
			}
		}
		return jsonArray;
	}
	
	/**
	 * 更新话题阅读数
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/1.0/subject/updatePv.do", method=RequestMethod.POST)
	public void updatePv(HttpServletRequest request, HttpServletResponse response) {
		WebUtils.setEncoding4App(request, response);
		
		String callback = AppControllerStatic.paramCallback(request);
        long subjectId = WebUtils.paramLong(request, "subjectId", 0L);
		
		JSONObject jsonObject = new JSONObject();
		
		//判断话题是否存在
		Subject subject = subjectService.findSubjectById(subjectId);
		if(subject == null) {
			AppControllerStatic.printErrorMsg(response, "话题不存在", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
			return;
		}
		long count = subject.getPvCount()+1;
        subject.setPvCount(count);
        int result =subjectService.updateByField( subject, "pv_count");
        if(result>0){
        	jsonObject.put("subjectId", subjectId);
        	jsonObject.put("pv", count);
        	AppControllerStatic.printSuccessMsg(response, "成功更新阅读数", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
        	return;
        }
        AppControllerStatic.printErrorMsg(response, "更新阅读数失败", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
	}
	
}
